package cn.fanqinghong.basic.controller;

import cn.fanqinghong.basic.exception.BusinessException;
import cn.fanqinghong.basic.util.AjaxResult;
import cn.fanqinghong.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 分布式文件接口
 * 1.上传接口
 * 2.删除接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")//group1/M00/00/04/CgAIC2Kl5zCAMEOUAATbNqt4dA0965.png
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            //得到文件名
            String filename = file.getOriginalFilename();//M00/00/04/CgAIC2Kl5zCAMEOUAATbNqt4dA0965.png
            //得到文件后缀名 以最后一个.+1个索引开始截取字符串
            String extName = filename.substring(filename.lastIndexOf(".") + 1);//png
            //使用工具类上传文件
            String path = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        }catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存失败"+e.getMessage());
        }
    }

    /**
     * 删除上传的文件
     * @param path
     * @return
     */
    @DeleteMapping//  http://localhost:8080/fastDfs?path=/group1/M00/00/04/CgAIC2Kl5zCAMEOUAATbNqt4dA0965.png
    public AjaxResult delete(@RequestParam String path){
            try {
                //获取文件的组类 何文件名,从索引1开始截取
                String pathTmp = path.substring(1);//结果 group1/M00/00/04/CgAIC2Kl5zCAMEOUAATbNqt4dA0965.png
                //获取到分组
                String group = pathTmp.substring(0, pathTmp.indexOf("/"));//group1
                //获取到文件名
                String fileName = pathTmp.substring(pathTmp.indexOf("/") + 1);//M00/00/04/CgAIC2Kl5zCAMEOUAATbNqt4dA0965.png
                //调用方法删除文件
                FastdfsUtil.delete(group,fileName);
                return AjaxResult.me();
            }catch (BusinessException e){
                e.printStackTrace();
                return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
            }catch (Exception e){
                e.printStackTrace();
                return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
            }
    }
}
